package com.zhixiang.wbl.visitor;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.zhixiang.wbl.visitor.ActivityManager.ScreenManager;
import com.zhixiang.wbl.visitor.Constant.Constant;
import com.zhixiang.wbl.visitor.Helper.BaseCallback;
import com.zhixiang.wbl.visitor.Helper.MyUserInfoProvider;
import com.zhixiang.wbl.visitor.Helper.OkHttpHelper;
import com.zhixiang.wbl.visitor.Helper.SpotsCallBack;
import com.zhixiang.wbl.visitor.Utils.NetworkUtils;
import com.zhixiang.wbl.visitor.Utils.URLUtil;
import com.zhixiang.wbl.visitor.Utils.VisitorUtil;
import com.zhixiang.wbl.visitor.activity.MainActivity;
import com.zhixiang.wbl.visitor.model.BaseModel;
import com.zhixiang.wbl.visitor.model.location.LocationModel;
import com.zhixiang.wbl.visitor.model.login.RootLogin;
import com.zhixiang.wbl.visitor.model.login.Visitor;
import com.zhixiang.wbl.visitor.model.token.RootToken;
import com.zhixiang.wbl.visitor.model.token.TokenModel;

import java.util.HashMap;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

public class LoginActivity extends Activity implements View.OnFocusChangeListener,View.OnClickListener
{
    @ViewInject(R.id.id_main_sv)
    ScrollView mainSV;
    @ViewInject(R.id.id_et_username)
    EditText usernameET;
    @ViewInject(R.id.id_et_password)
    EditText passwordET;
    @ViewInject(R.id.id_whole_rl)
    RelativeLayout whole_RL;
    @ViewInject(R.id.id_button_login)
    Button mLoginButton;
    @ViewInject(R.id.id_button_logout)
    Button mLogoutButton;
    private final static String TAG = "LoginActivity";
    private OkHttpHelper httpHelper = OkHttpHelper.getInstance();
    private Visitor mVisitor = null;

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ViewUtils.inject(this);
        //起始动画
        annimationWhenStart();
        initEditTextListenner();
        initButtonListnener();
        initLocationParamters();
        //将当前Actitity放入堆栈
        ScreenManager.getScreenManager().pushActivity(this);
    }

  //登录界面启动动画
  private void annimationWhenStart()
  {
      ObjectAnimator animator =  ObjectAnimator.ofFloat(mainSV, "rotationX", 0.0F, 360.0F)
              .setDuration(500);
      animator.setRepeatCount(1);
      animator.addListener(new AnimatorListenerAdapter() {
          @Override
          public void onAnimationEnd(Animator animation)
          {
              float w = Float.parseFloat(Integer.toString(mainSV.getWidth()));
              float h = Float.parseFloat(Integer.toString(mainSV.getHeight()));
              int [] location = new int[2];
              mainSV.getLocationOnScreen(location);
          }
      });
      animator.start();
  }
    /*
    * 初始化用户名和密码输入框监听事件,以及初始化数据
    * */
    private void initEditTextListenner()
    {
        /*
        * 从缓存中获取数据，更新UI
        * */
       // SharedPreferences sp = this.getSharedPreferences(Constant.USER_INFO,MODE_PRIVATE);
        Visitor visitor = VisitorUtil.getCurrentVisitor(getApplicationContext());
        if (visitor!=null)
        {
            String username = visitor.getUsername();  //sp.getString(Constant.USER_NAME_KEY,"");
            String password = visitor.getPassword();  //sp.getString(Constant.PASSWORD_KEY,"");

            usernameET.setText(username);
            passwordET.setText(password);
        }
        usernameET.setOnFocusChangeListener(this);
        passwordET.setOnFocusChangeListener(this);
    }

   /*
   * 设置按钮监听事件
   * */
   public void initButtonListnener()
   {
     mLoginButton.setOnClickListener(this);
     mLogoutButton.setOnClickListener(this);
   }
    @Override
    public void onClick(View v)
    {
      switch (v.getId())
      {
          case R.id.id_button_login:
              login();
              //gotoMainAcitivity();
              break;
          case R.id.id_button_logout:
              logout();
              break;

      }
    }
   /*
   * 跳转到主界面
   * */
    private void gotoMainAcitivity()
    {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.putExtra(Constant.CURRENT_VISITOR_KEY,mVisitor);
        startActivity(intent);
    }
    @Override
    public void onFocusChange(View v, boolean hasFocus)
    {
        int[] location = new int[2];
        mainSV.getLocationOnScreen(location);

        whole_RL.getLocationOnScreen(location);

    }
    public void login()
    {
      String username = usernameET.getText().toString();
      String password = passwordET.getText().toString();
      username.trim();
      password.trim();
      Map<String,String> params = new HashMap<>();
      params.put(Constant.USER_NAME_KEY,username);
      params.put(Constant.PASSWORD_KEY,password);
      String url = URLUtil.getURL(Constant.LOGIN_URL,params);
      httpHelper.get(url, new SpotsCallBack<RootLogin>(this,"正在登录")
      {
          @Override
          public void onSuccess(Response response, RootLogin rootLogin)
          {
            //  Log.e(TAG, "onSuccess:"+rootLogin.toString());
              if (rootLogin.getCode() == 200)
              {
                  //登录成功后对数据进行缓存
                  mVisitor = rootLogin.getData();
                  mLocationClient.start();

                  //缓存用户信息
                  VisitorUtil.cacheVistorInfo(mVisitor,getApplicationContext());

                  //通知登录成功
                  Message message = new Message();
                  message.what = 1;
                  mLoginHandler.sendMessage(message);
              }
          }
          @Override
          public void onError(Response response, int code, Exception e)
          {
               // Toast.makeText()
              //先判断当前网络是否可用
             boolean isNetworkAvable =   NetworkUtils.isNetworkAvailable(getApplicationContext());
              if (isNetworkAvable)
              {
                  Toast.makeText(LoginActivity.this,"用户名或者密码错误",Toast.LENGTH_SHORT).show();
              }
              else
              {
                  Toast.makeText(LoginActivity.this,"网络不可用，请检查网络",Toast.LENGTH_SHORT).show();
              }
          }
      });
    }

  private Handler mLoginHandler = new Handler()
  {
      @Override
      public void handleMessage(Message msg) {
          super.handleMessage(msg);
          if (msg.what == 1)//用于处理登录操作
          {
              //1先是获取Token
              //2连接容云服务器
              //3跳转到主界面
              getToken();
             // connect(mVisitor.);
            //  gotoMainAcitivity();
          }
          else if (msg.what==2)
          {
              String token = (String) msg.obj;
              connect(token);
          }
          else if (msg.what ==3)
          {
              gotoMainAcitivity();
          }
      }
  };
    /*
    * 获取Token
    * @param visitorid 游客id
    * @param username 游客的用户名
    * */
    private void getToken()
    {
        //先读取缓存
        TokenModel token1 = VisitorUtil.getToken(getApplicationContext());
        if (token1!=null)
        {
            //连接融云服务器
            Message msg = new Message();
            msg.obj = token1.getToken();
            msg.what = 2;
            mLoginHandler.sendMessage(msg);
            return;
        }
        //拼接接口字符串
        Map<String,String> map = new HashMap<>();
        map.put("visitorid",mVisitor.getId()+"");
        map.put("username",mVisitor.getUsername());
        String url = URLUtil.getURL(Constant.Token_GET_URL,map);
       // Log.e(TAG, "getToken: "+url );

        httpHelper.get(url, new SpotsCallBack<RootToken>(this,"正在连接服务器。。。") {
            @Override
            public void onSuccess(Response response, RootToken rootToken)
            {
                Toast.makeText(LoginActivity.this,"连接成功",Toast.LENGTH_SHORT).show();
                if (200 == rootToken.getCode())
                {
                    //获取到token
                    TokenModel token = rootToken.getData();
                    //缓存token
                    VisitorUtil.cacheToken(getApplicationContext(),token);
                  //连接融云服务器
                    Message msg = new Message();
                    msg.obj = token.getToken();
                    msg.what = 2;
                    mLoginHandler.sendMessage(msg);
                }
            }

            @Override
            public void onError(Response response, int code, Exception e) {
                Toast.makeText(LoginActivity.this,"连接服务器失败",Toast.LENGTH_SHORT).show();
            }
        });
    }
    /*
      * 初始化定位
      * */
    public void initLocationParamters()
    {
        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener( myListener );    //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span=1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);

    }
    /*
     * 更新用户位置
     * */
    private void updateUserCurrentLocation(double latitude,double longtitude)
    {
        //先缓存下用户位置
        LocationModel locationM = new LocationModel();
        locationM.setId("0");
        locationM.setLatitude(latitude+"");
        locationM.setLongtitude(longtitude+"");
        locationM.setType(1+"");
        locationM.setUser_id(mVisitor.getId()+"");

        VisitorUtil.cacheLocation(getApplicationContext(),locationM);
        //接着跟新服务器上的用户数据
        Map<String,String> map = new HashMap<>();
        map.put("latitude",latitude+"");
        map.put("longtitude",longtitude+"");
        map.put("user_id",mVisitor.getId()+"");
        String url = URLUtil.getURL(Constant.UPDATE_VISITOR_LOCATION,map);
        httpHelper.get(url, new BaseCallback<BaseModel>()
        {
            @Override
            public void onBeforeRequest(Request request)
            {

            }
            @Override
            public void onFailure(Request request, Exception e)
            {

            }

            @Override
            public void onResponse(Response response)
            {

            }

            @Override
            public void onSuccess(Response response, BaseModel rootLocation)
            {
                if (200 == rootLocation.getCode())
                    Log.e(TAG, "onSuccess:"+rootLocation.getMessage());
            }

            @Override
            public void onError(Response response, int code, Exception e)
            {
                Log.e(TAG, "失败了");
            }
        });
    }

    /*
    * 退出应用
    * */
  private void logout()
  {
      
//      Intent intent = new Intent(LoginActivity.this, MapviewActivity.class);
//      startActivity(intent);
  }

    @Override
    public void finish()
    {
        super.finish();
    }

    public class MyLocationListener implements BDLocationListener
    {

        @Override
        public void onReceiveLocation(BDLocation location)
        {
            //Receive Location
            if (location!=null)
            {
                double latitude = location.getLatitude();
                double longtitude = location.getLongitude();
             //   Log.e(TAG, "onReceiveLocation: "+"latitude:"+latitude+" " +
           //             "longtitude:"+longtitude );
                updateUserCurrentLocation(latitude,longtitude);
            }
        }
    }
    /**
     * 建立与融云服务器的连接
     *
     * @param token
     */
    private void connect(String token) {
        //Log.e(TAG, "connect: "+"12" );
        if (getApplicationInfo().packageName.equals(MyApplication.getCurProcessName(getApplicationContext()))) {
       //     Log.e(TAG, "connect: "+"123" );
            /**
             * IMKit SDK调用第二步,建立与服务器的连接
             */
            RongIM.connect(token, new RongIMClient.ConnectCallback() {

                /**
                 * Token 错误，在线上环境下主要是因为 Token 已经过期，您需要向 App Server 重新请求一个新的 Token
                 */
                @Override
                public void onTokenIncorrect() {

                    Log.d("LoginActivity", "--onTokenIncorrect");
                }

                /**
                 * 连接融云成功
                 * @param userid 当前 token
                 */
                @Override
                public void onSuccess(String userid)
                {

                    mLoginHandler.sendEmptyMessage(3);
                    RongIM.setUserInfoProvider(new MyUserInfoProvider(getApplicationContext()),true);

//                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
//                    finish();
                }

                /**
                 * 连接融云失败
                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
                 */
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                    Log.d("LoginActivity", "--onError" + errorCode);
                }
            });
        }
    }
}
